package com.jweb.framework.ws.client;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPFault;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.transport.WebServiceConnection;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：spring-ws 第三方模板类
 */
public class WebServiceTemplateJWeb extends WebServiceTemplate {
	
	public WebServiceTemplateJWeb(){
		
	}
	
	public WebServiceTemplateJWeb(WebServiceMessageFactory webServiceMessageFactory){
		super(webServiceMessageFactory);
	}
	
	/**酒店返回SOAP异常处理*/
	@Override
	protected Object handleFault(WebServiceConnection connection, MessageContext messageContext) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Fault message for request [" + messageContext.getRequest() + "]");
        }
        if (getFaultMessageResolver() != null) {
            //getFaultMessageResolver().resolveFault(messageContext.getResponse());
            //return null;
            return parseFaultToMap(messageContext.getResponse());
        }
        else {
            return handleError(connection, messageContext.getRequest());
        }
    }
	
	private Map parseFaultToMap(WebServiceMessage message) throws IOException {
		
		SoapMessage soapMessage = (SoapMessage) message;
		SOAPFault soapFault ;
		Map faultMap = new HashMap();
		
		if(soapMessage instanceof com.jweb.framework.ws.soap.axiom.AxiomSoapMessage){
			soapFault = ((com.jweb.framework.ws.soap.axiom.AxiomSoapMessage)soapMessage).getAxiomMessage().getSOAPEnvelope().getBody().getFault();
			String faultcodeKey = soapFault.getCode().getLocalName();
			String faultcodeVal = soapFault.getCode().getText();
			faultMap.put(faultcodeKey, faultcodeVal);
			
			String faultstringKey = soapFault.getReason().getLocalName();
			String faultstringVal = soapFault.getReason().getText();
			faultMap.put(faultstringKey, faultstringVal);
			
			for(Iterator it = soapFault.getDetail().getAllDetailEntries() ; it.hasNext() ;){
				OMElement om = ((OMElement)it.next());
				String exName = om.getLocalName(); 
				faultMap.put("exName", exName);
				
				for(Iterator it111 = om.getChildElements(); it111.hasNext() ;){
					OMElement om2 = ((OMElement)it111.next());
					String errCode = om2.getLocalName();
					String errMsg = om2.getText();
					faultMap.put(errCode , errMsg);
				}
			}
			return faultMap ;
		}
		throw new IllegalArgumentException("Message type not supported [" + soapMessage + "]");
	}
	
}
